﻿using AhpilyServer;
using System.Collections.Generic;
using System.Linq;

namespace PokerServer.Cache.Match
{
    /// <summary>
    /// 匹配房间
    /// </summary>
    public class MatchRoom
    {
        public int Id { get; } // 唯一标识

        /// <summary>
        /// 在房间内用户id的列表
        /// </summary>
        public Dictionary<int, ClientPeer> UIdClientDict { get; }

        public List<int> GetUiList()
        {
            return UIdClientDict.Keys.ToList();
        }


        public readonly List<int> readyUIdList;

        public MatchRoom(int id)
        {
            Id = id;
            UIdClientDict = new Dictionary<int, ClientPeer>();
            readyUIdList = new List<int>();
        }

        /// <summary>
        /// 房间是否满了
        /// </summary>
        /// <returns></returns>
        public bool IsFull()
        {
            return UIdClientDict.Count == 3;
        }

        /// <summary>
        /// 房间是否为空
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            return UIdClientDict.Count == 0;
        }

        /// <summary>
        /// 是否所有人都准备了
        /// </summary>
        /// <returns></returns>
        public bool IsAllReady()
        {
            return readyUIdList.Count == 3;
        }

        /// <summary>
        /// 进入房间
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="client"></param>
        public void Enter(int userId, ClientPeer client)
        {
            UIdClientDict.Add(userId, client);
        }

        /// <summary>
        /// 离开房间
        /// </summary>
        /// <param name="userId"></param>
        public void Leave(int userId)
        {
            UIdClientDict.Remove(userId);
        }

        /// <summary>
        /// 玩家准备
        /// </summary>
        /// <param name="userId"></param>
        public void Ready(int userId)
        {
            readyUIdList.Add(userId);
        }

        /// <summary>
        /// 广播房间内的所有玩家信息
        /// 除了自己
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="subCode"></param>
        /// <param name="value"></param>
        /// <param name="exClient"></param>
        public void Brocast(int opCode, int subCode, object value, ClientPeer exClient = null)
        {
            SocketMsg msg = new SocketMsg(opCode, subCode, value);

            byte[] data = EncodeTool.EncodeMsg(msg);
            byte[] packet = EncodeTool.EncodePacket(data);

            foreach (ClientPeer client in UIdClientDict.Values)
            {
                if (client == exClient)
                {
                    continue;
                }

                client.Send(packet);
            }
        }
    }
}